package com.team2.insulatingtools.modular.tools.service.impl;

import cn.stylefeng.roses.kernel.auth.api.context.LoginContext;
import cn.stylefeng.roses.kernel.office.api.OfficeExcelApi;
import cn.stylefeng.roses.kernel.office.api.pojo.report.ExcelExportParam;
import cn.stylefeng.roses.kernel.rule.pojo.response.ErrorResponseData;
import cn.stylefeng.roses.kernel.rule.pojo.response.ResponseData;
import cn.stylefeng.roses.kernel.rule.pojo.response.SuccessResponseData;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mysql.cj.util.StringUtils;
import com.team2.insulatingtools.modular.system.entity.ToolsHrOrganization;
import com.team2.insulatingtools.modular.system.service.OrgService;
import com.team2.insulatingtools.modular.tools.entity.Tools;
import com.team2.insulatingtools.modular.tools.mapper.RecordStatisticsMapper;
import com.team2.insulatingtools.modular.tools.pojo.request.ToolDetailAddRequest;
import com.team2.insulatingtools.modular.tools.pojo.request.ToolDetailRequest;
import com.team2.insulatingtools.modular.tools.pojo.request.ToolsRequest;
import com.team2.insulatingtools.modular.tools.pojo.response.RecordStatisticsDetailResponse;
import com.team2.insulatingtools.modular.tools.pojo.response.RecordStatisticsExportExcel;
import com.team2.insulatingtools.modular.tools.pojo.response.RecordStatisticsImportResultsExcel;
import com.team2.insulatingtools.modular.tools.pojo.response.RecordStatisticsResponse;
import com.team2.insulatingtools.modular.tools.service.RecordStatisticsService;
import com.team2.insulatingtools.modular.tools.service.ToolDetailService;
import com.team2.insulatingtools.modular.tools.service.ToolsService;
import org.apache.http.client.utils.DateUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * .           ,%%%%%%%%,
 * .         ,%%/\%%%%/\%%
 * .        ,%%%\c "" J/%%%
 * %.       %%%%/ o  o \%%%
 * `%%.     %%%%    _  |%%%
 * `%%      `%%%%(__Y__)%%'
 * //        ;%%%%`\-/%%%'
 * ((        /  `%%%%%%%'
 * \\    .'          |
 * \\  /       \  | |
 * \\/         ) | |
 * \         /_ | |__
 * (___________)))))))
 * 攻城狮 永无bug!
 *
 * @ClassName RecordStatisticsServiceImpl
 * @Author lemon
 * @create 2023/4/6 15:17
 */
@Service
public class RecordStatisticsServiceImpl implements RecordStatisticsService {

    @Resource
    RecordStatisticsMapper dao;

    @Resource
    OfficeExcelApi officeExcelApi;

    @Resource
    ToolsService toolsService;

    @Resource
    ToolDetailService toolDetailService;


    @Override
    public List<RecordStatisticsResponse> showRecordStatistics(String orgName, String toolName) {

        List<Integer> toolsIdList = new ArrayList<>();
        //如果orgName不为空，则按照orgName返回数据，如果空，则获得当前登录角色的所以有权限
        if (orgName != null && !orgName.equals("")) {
            toolsIdList = dao.getToolsIdByName(orgName);
        } else {
            Long organizationId = LoginContext.me().getLoginUser().getOrganizationId();
            toolsIdList = dao.getToolsIdById(organizationId);
        }
        //如果未指定工具名称，则显示所有工具
        if (toolName == null || toolName.equals("")) {
            toolName = "";
        }
        List<RecordStatisticsResponse> recordStatisticsResponseList = new ArrayList<>();
        //根据id在数据库嵌套查询拼接
        for (Integer toolsId : toolsIdList) {
            RecordStatisticsResponse recordStatistics = dao.getRecordStatisticsList(toolsId, toolName);
            //差不到相应数据则跳过
            if(recordStatistics==null)
            {
                continue;
            }
            int index = recordStatistics.getToolDetailList().size()-1;
            //删除id为空的工具详情脏数据
            while (index >= 0) {
                if(recordStatistics.getToolDetailList().get(index).getId()==null || recordStatistics.getToolDetailList().get(index).getId().equals(""))
                {
                    recordStatistics.getToolDetailList().remove(index);
                }
                index--;
            }
            //每个结果组合成list
            if (recordStatistics != null) {
                recordStatisticsResponseList.add(recordStatistics);
            }

        }

        return recordStatisticsResponseList;

    }

    @Override
    public void exportExcel(HttpServletResponse response, List<RecordStatisticsResponse> recordStatisticsList) {
        List<RecordStatisticsExportExcel> list = new ArrayList<>();
        for (RecordStatisticsResponse recordStatistics : recordStatisticsList) {
            RecordStatisticsExportExcel exportExcel = new RecordStatisticsExportExcel();
            if (recordStatistics != null) {
                //将recordStatistics的值赋给exportExcel
                exportExcel = JSONObject.parseObject(JSONObject.toJSONStringWithDateFormat(recordStatistics, "yyyy-MM-dd"), RecordStatisticsExportExcel.class);
                list.add(exportExcel);
                if (recordStatistics.getToolDetailList() != null && !recordStatistics.getToolDetailList().isEmpty()) {
                    for (RecordStatisticsDetailResponse detailResponse : recordStatistics.getToolDetailList()) {
                        RecordStatisticsExportExcel exportExcel1 = new RecordStatisticsExportExcel();
                        //将recordStatistics的值赋给exportExcel
                        exportExcel1 = JSONObject.parseObject(JSONObject.toJSONStringWithDateFormat(detailResponse, "yyyy-MM-dd"), RecordStatisticsExportExcel.class);
                        //设置子工具的父id
                        exportExcel1.setParentToolNumber(exportExcel.getNumber());
                        list.add(exportExcel1);
                    }
                }
            }
        }
        ExcelExportParam excelExportParam = new ExcelExportParam();
        excelExportParam.setDataList(list);
        excelExportParam.setClazz(RecordStatisticsExportExcel.class);
        excelExportParam.setSheetName("记录");
        excelExportParam.setFileName("记录统计" + System.currentTimeMillis());
        excelExportParam.setResponse(response);
        officeExcelApi.easyExportDownload(excelExportParam);
    }

    @Override
    public void importExcel(MultipartFile file, HttpServletResponse response) throws IOException {

        List<RecordStatisticsExportExcel> excelList = officeExcelApi.easyReadToList(file.getInputStream(), RecordStatisticsExportExcel.class);
        List<RecordStatisticsImportResultsExcel> resultsExcels = new ArrayList<>();

        Long organizationId = LoginContext.me().getLoginUser().getOrganizationId();
        List<String> orgNameList = dao.getToolsOrgNameById(organizationId);

        ResponseData<?> add = new ResponseData<>();


        //判断数值类型
        for (RecordStatisticsExportExcel excel : excelList) {
            //通过班组获取quotaid和toolid
            Integer quotaId = dao.getQuotaIdByTeamName(excel.getTeamName(), excel.getName());
            if(excel.getNumber()==null || excel.getNumber().equals(""))
            {
                RecordStatisticsImportResultsExcel resultsExcel = JSONObject.parseObject(JSONObject.toJSONStringWithDateFormat(excel, "yyyy-MM-dd"), RecordStatisticsImportResultsExcel.class);
                resultsExcel.setImportResults("编号为空！");
                resultsExcels.add(resultsExcel);
                continue;
            }
            String[] split = excel.getNumber().split("-");
            Integer toolId = dao.getToolIdByTeamName(excel.getTeamName(), excel.getName(),split[0]);
            if (excel.getParentToolNumber().equals("-1")) {
                //判断车间班组有无权限
                if (!orgNameList.contains(excel.getWorkShopName()) || !orgNameList.contains(excel.getWorkShopName())) {
                    RecordStatisticsImportResultsExcel resultsExcel = JSONObject.parseObject(JSONObject.toJSONStringWithDateFormat(excel, "yyyy-MM-dd"), RecordStatisticsImportResultsExcel.class);
                    resultsExcel.setImportResults("无权限的数据");
                    resultsExcels.add(resultsExcel);
                    continue;
                }
                if(toolId==null || toolId.equals(""))
                {
                    RecordStatisticsImportResultsExcel resultsExcel = JSONObject.parseObject(JSONObject.toJSONStringWithDateFormat(excel, "yyyy-MM-dd"), RecordStatisticsImportResultsExcel.class);
                    resultsExcel.setImportResults("车间班组信息或工具编号信息有误");
                    resultsExcels.add(resultsExcel);
                    continue;
                }
                //判断tool编号是否重复
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("id", toolId);

                if (toolsService.list(queryWrapper).size() != 0) {
                    RecordStatisticsImportResultsExcel resultsExcel = JSONObject.parseObject(JSONObject.toJSONStringWithDateFormat(excel, "yyyy-MM-dd"), RecordStatisticsImportResultsExcel.class);
                    resultsExcel.setImportResults("工具编号重复！");
                    resultsExcels.add(resultsExcel);
                    continue;
                }

                ToolsRequest toolsRequest = JSONObject.parseObject(JSONObject.toJSONStringWithDateFormat(excel, "yyyy-MM-dd"), ToolsRequest.class);
                toolsRequest.setQuotaId(quotaId);
                add = toolsService.add(toolsRequest);
            } else {
                if(toolId==null || toolId.equals(""))
                {
                    RecordStatisticsImportResultsExcel resultsExcel = JSONObject.parseObject(JSONObject.toJSONStringWithDateFormat(excel, "yyyy-MM-dd"), RecordStatisticsImportResultsExcel.class);
                    resultsExcel.setImportResults("车间班组信息或工具编号信息有误");
                    resultsExcels.add(resultsExcel);
                    continue;
                }
                //判断detail编号是否重复
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("tool_id", toolId);
                queryWrapper.eq("number",excel.getNumber());
                List list = toolDetailService.list(queryWrapper);
                if (toolDetailService.list(queryWrapper).size() != 0) {
                    RecordStatisticsImportResultsExcel resultsExcel = JSONObject.parseObject(JSONObject.toJSONString(excel), RecordStatisticsImportResultsExcel.class);
                    resultsExcel.setImportResults("工具详情编号重复！");
                    resultsExcels.add(resultsExcel);
                    continue;
                }
                ToolDetailAddRequest toolDetailAddRequest = new ToolDetailAddRequest(toolId, excel.getNumber());
                add = toolDetailService.addToolsDetail(toolDetailAddRequest);
            }

            if (add.getSuccess()) {
                RecordStatisticsImportResultsExcel resultsExcel = JSONObject.parseObject(JSONObject.toJSONString(excel), RecordStatisticsImportResultsExcel.class);
                resultsExcel.setImportResults("成功");
                resultsExcels.add(resultsExcel);
            } else {
                RecordStatisticsImportResultsExcel resultsExcel = JSONObject.parseObject(JSONObject.toJSONStringWithDateFormat(excel, "yyyy-MM-dd"), RecordStatisticsImportResultsExcel.class);
                resultsExcel.setImportResults(add.getMessage());
                resultsExcels.add(resultsExcel);
            }
        }
        ExcelExportParam excelExportParam = new ExcelExportParam();
        excelExportParam.setDataList(resultsExcels);
        excelExportParam.setClazz(RecordStatisticsImportResultsExcel.class);
        excelExportParam.setSheetName("记录导入结果");
        excelExportParam.setFileName("记录统计导入结果" + System.currentTimeMillis());
        excelExportParam.setResponse(response);
        officeExcelApi.easyExportDownload(excelExportParam);
    }
}
